"""
重构后的Signals - 大幅简化逻辑
由于TaskDefinition已经直接关联了Celery调度表,这里只需要处理PeriodicTask的创建/更新/删除
"""
from django.db.models.signals import post_save, pre_delete, post_delete
from django.dispatch import receiver
from django_celery_beat.models import PeriodicTask
from celery import current_app
import json
from .models import Tasks
import logging

logger = logging.getLogger(__name__)


@receiver(post_save, sender=Tasks)
def sync_periodic_task(sender, instance, created, **kwargs):
    """
    同步创建/更新 PeriodicTask
    逻辑大幅简化:直接使用TaskDefinition中已配置好的调度
    """
    logger.info(f"Signal triggered for Tasks: {instance.id}, PeriodicTask: {instance.celery_task_id},created: {created}")
    
    # 避免递归调用
    if kwargs.get('update_fields') == ['celery_task_id']:
        return
    
    # 一次性任务直接执行,不创建PeriodicTask
    if instance.task_definition.task_type == 'once':
        if instance.enabled:  # 只在启用时执行
            task_kwargs = {'tasks_instance_id': instance.id, 'periodic_task_name': instance.name, **instance.task_kwargs}
            current_app.send_task(
                instance.task_func,
                args=instance.task_args,
                kwargs=task_kwargs
            )
        return
    
    # 准备PeriodicTask数据
    task_kwargs = {'tasks_instance_id': instance.id, **instance.task_kwargs}
    args_json = json.dumps(instance.task_args) if instance.task_args else '[]'
    kwargs_json = json.dumps(task_kwargs) if task_kwargs else '{}'
    
    # 获取或创建PeriodicTask
    if instance.celery_task_id:
        try:
            periodic_task = PeriodicTask.objects.get(id=instance.celery_task_id)
        except PeriodicTask.DoesNotExist:
            periodic_task = None
    else:
        periodic_task = None
    
    # 从TaskDefinition获取调度配置
    task_def = instance.task_definition
    
    if periodic_task is None:
        # 创建新的PeriodicTask
        periodic_task = PeriodicTask.objects.create(
            name=instance.name,
            task=instance.task_func,
            crontab=task_def.crontab,
            interval=task_def.interval,
            clocked=task_def.clocked,
            one_off=task_def.task_type == 'clock',  # 时钟任务是一次性的
            args=args_json,
            kwargs=kwargs_json,
            enabled=instance.enabled,
            description=instance.description or f"{task_def.name}-{instance.task_func}"
        )
        # 更新celery_task_id
        Tasks.objects.filter(id=instance.id).update(celery_task_id=periodic_task.id)
        logger.info(f"PeriodicTask created: {periodic_task.id}")
    else:
        # 更新现有的PeriodicTask
        periodic_task.name = instance.name
        periodic_task.task = instance.task_func
        periodic_task.crontab = task_def.crontab
        periodic_task.interval = task_def.interval
        periodic_task.clocked = task_def.clocked
        periodic_task.one_off = task_def.task_type == 'clock'
        periodic_task.args = args_json
        periodic_task.kwargs = kwargs_json
        periodic_task.enabled = instance.enabled
        periodic_task.description = instance.description or f"{task_def.name}-{instance.task_func}"
        periodic_task.save()
        logger.info(f"PeriodicTask updated: {periodic_task.id}")


@receiver(pre_delete, sender=Tasks)
def delete_periodic_task(sender, instance, **kwargs):
    """删除Tasks时同步删除PeriodicTask"""
    if instance.celery_task_id:
        try:
            PeriodicTask.objects.filter(id=instance.celery_task_id).delete()
        except PeriodicTask.DoesNotExist:
            pass
